#include "application.h"

inline void Application::showUsage() const
{
    printf("Usage: render [sce file] [out file] [width] [height] (-rec [rec_level]) (-antialiasing)\n");;
}

inline bool Application::processOptions()
{
    bool res(false);

    if( argc < 5 )
        showUsage();
    else
    {
        res     = true;
        sceFile = std::string(argv[1]);
        outFile = std::string(argv[2]);
        width   = atoi(argv[3]);
        height  = atoi(argv[4]);
        for(int n=5 ; n < argc ; n++ )
        {
            if( !strcmp(argv[n],"-antialiasing"))
                antialiasing = true;
            else if( !strcmp(argv[n],"-anaglyph"))
                anaglyph = true;
            else if( !strcmp(argv[n],"-rec"))
            {
                if( argc > n )
                {
                    n++;
                    recursivityLevel = atoi(argv[n]);
                }
                else
                    printf("[Warning] you should precise the recursivity level after the option '-rec'\n");
            }
            else
                printf("[Warning] %sc- unknow option\n",argv[n]);
        }
    }
    return res;
}

inline int Application::exec()
{
    int res(1);
    Chrono chrono;
    if( processOptions() )
    {
        res = 0;
        try
        {
            if( anaglyph )
            {
                Anaglyph anaglyph( width,height,recursivityLevel,antialiasing);
                anaglyph.load(sceFile);
                anaglyph.setAnaglyphSettings(Color(1.0,0.0,0.0),Color(0.0,1.0,1.0),anaglyph.getAutoFocus());
                chrono.start();
                anaglyph.render(outFile);
                chrono.stop();
            }
            else
            {

                RayTracer raytracer(width,height,recursivityLevel,antialiasing);
                raytracer.load(sceFile);
                chrono.start();
                raytracer.render(outFile);
                chrono.stop();
            }
            printf("Rendered in %i ms\n",chrono.time_ms());
        }
        catch(const Exception &e)
        {
            printf("Error: %s",e.what());
            printf("\n");
        }


    }
    return res;
}
